import type { FlowNode, FlowEdge, JDFAttribute } from '@/models/jdf';

/**
 * Generates an XML string from the flow elements data.
 * @param nodes All nodes in the flow.
 * @param edges All edges in the flow.
 * @param rootNodeId The ID of the root node to start generation from.
 * @returns The generated XML string.
 */
export function generateXmlFromFlow(nodes: FlowNode[], edges: FlowEdge[], rootNodeId: string): string {
    const nodeMap = new Map<string, FlowNode>(nodes.map(n => [n.id, n]));
    const childrenMap = new Map<string, string[]>(); // Map<parentId, childId[]>

    // Build children map from edges
    edges.forEach(edge => {
        if (!childrenMap.has(edge.source)) {
            childrenMap.set(edge.source, []);
        }
        childrenMap.get(edge.source)!.push(edge.target);
    });

    // Recursive function to build XML for a node and its descendants
    const buildNodeXml = (nodeId: string, indentLevel: number = 0): string => {
        const node = nodeMap.get(nodeId);
        if (!node) return ''; // Should not happen if data is consistent

        const indent = '  '.repeat(indentLevel);
        let xml = `${indent}<${node.data.nodeName}`;

        // Add attributes
        node.data.attributes.forEach(attr => {
            // Basic XML escaping for attribute values
            const escapedValue = attr.value
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/\"/g, '&quot;')
                .replace(/\'/g, '&apos;');
            xml += ` ${attr.name}="${escapedValue}"`;
        });

        const childrenIds = childrenMap.get(nodeId) || [];
        const textContent = node.data.textContent?.trim();

        if (childrenIds.length === 0 && !textContent) {
            // Self-closing tag
            xml += '/>\n';
        } else {
            xml += '>';
            if (childrenIds.length > 0) {
                xml += '\n';
                childrenIds.forEach(childId => {
                    xml += buildNodeXml(childId, indentLevel + 1);
                });
                xml += `${indent}</${node.data.nodeName}>\n`;
            } else if (textContent) {
                // Basic XML escaping for text content
                 const escapedText = textContent
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;');
                xml += `${escapedText}</${node.data.nodeName}>\n`;
            }
        }
        return xml;
    };

    // Start building from the root node
    const generatedXml = buildNodeXml(rootNodeId);

    // Add XML declaration (optional, but good practice)
    return `<?xml version="1.0" encoding="UTF-8"?>
${generatedXml}`;
} 